package space.pyq.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.model.Response;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.sharesdk.onekeyshare.OnekeyShare;
import space.pyq.R;
import space.pyq.dlna.DlnaActivty;
import space.pyq.view.HTML5WebView;

/**
 * Created by Administrator on 2016/4/7.
 * 自定义的webview HTML5WebView
 * 乐视网页有时加载失败 神州行手机播放网页视频有声音没画面
 */
public class CustomWebViewActivity extends DlnaActivty {

    private static final String TAG = "CustomWebViewActivity";
    FrameLayout mFrameLayoutLoadingHtml5;

    private String webviewUrl;
    private HTML5WebView mWebView;
    private RelativeLayout rlStart;
    private ImageView ivStart;

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setContentView(R.layout.custom_webview_layout);
        mFrameLayoutLoadingHtml5 = (FrameLayout) findViewById(R.id.frameLayout_loading_html5);
        rlStart = (RelativeLayout) findViewById(R.id.rl_start);
        ivStart = (ImageView) findViewById(R.id.iv_start);
        initDlnaService();
        webviewUrl = getIntent().getStringExtra("webviewUrl");
        if (TextUtils.isEmpty(webviewUrl)) {
            webviewUrl = "https://www.51ypq.com/";
        }
        initView(savedInstanceState);
        mWebView.addJavascriptInterface(new JavascriptPlugin(), "android");

        initStartImg();
        hideStatusBar();
    }

    private void initStartImg() {
        timer.start();
        String imgPath = getExternalFilesDir("/download/").getAbsolutePath() + "/start.jpg";
        Bitmap startImg = BitmapFactory.decodeFile(imgPath);
        if (startImg==null){
            ivStart.setImageResource(R.drawable.start);
        }else{
            ivStart.setImageBitmap(startImg);
        }
        downloadImg("https://www.51ypq.com/cms/uploadFile/image/kaijidaotu.png");
    }

    private void initView(Bundle savedInstanceState) {
        mWebView = new HTML5WebView(this);
        mWebView.setBackgroundColor(this.getResources().getColor(android.R.color.transparent));
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        Log.d("webView url = ", webviewUrl);

        mWebView.loadUrl(webviewUrl);
        mFrameLayoutLoadingHtml5.addView(mWebView.getLayout());

        if (savedInstanceState != null) {
            mWebView.restoreState(savedInstanceState);
        }
        handler.sendEmptyMessageDelayed(100, 10 * 1000);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

//            playVideo("测试测试", "http://36.111.40.37:17553/Ypq/jbh_yezishu.mp4");
            showShare();
        }
    };

    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // 启动分享GUI
        oks.show(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //机顶盒的返回键监听是KEYCODE_ESCAPE
        if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack()) {
                mWebView.goBack(); // goBack()表示返回WebView的上一页面
                return true;
            } else {
                finish();
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            ViewGroup parent = (ViewGroup) mWebView.getParent();
            if (parent != null) {
                parent.removeView(mWebView);
            }
            mWebView.removeAllViews();
            mWebView.destroy();
        }
        super.onDestroy();
    }

    protected void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    protected void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    @Override
    public void onStop() {
        super.onStop();
        mWebView.stopLoading();
    }

    private final class JavascriptPlugin {

        //吊起本地播放视频
        @JavascriptInterface
        public void playVideo(String name, String playUrl) {
            Intent intent = new Intent(CustomWebViewActivity.this, PlayActivity.class);
            intent.putExtra("name", name);
            intent.putExtra("playUrl", playUrl);
            CustomWebViewActivity.this.startActivity(intent);
        }

    }

    public void playVideo(String name, String playUrl) {
        Intent intent = new Intent(CustomWebViewActivity.this, PlayActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("playUrl", playUrl);
        CustomWebViewActivity.this.startActivity(intent);
    }


    public void downloadImg(final String url) {
        OkGo.<Bitmap>get(url).cacheMode(CacheMode.NO_CACHE).tag(this).execute(new BitmapCallback() {
            @Override
            public void onSuccess(Response<Bitmap> response) {
                if (rlStart.getVisibility()==View.VISIBLE){
                    ivStart.setImageBitmap(response.body());
                }
                String imgPath = getExternalFilesDir("/download/").getAbsolutePath() + "/start.jpg";
                saveBitmap(response.body(), imgPath);
            }
        });
    }

    public void saveBitmap(Bitmap bitmap, String path) {
        Log.e(TAG, "保存图片");
        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i(TAG, "已经保存");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    CountDownTimer timer = new CountDownTimer(6 * 1000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            rlStart.setVisibility(View.GONE);
            showStatusBar();
        }
    };

    public void onClick(View view) {
        if (view.getId() == R.id.btn_go) {
            rlStart.setVisibility(View.GONE);
            timer.cancel();
            showStatusBar();
        }
    }

    private void hideStatusBar() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏
    }

    private void showStatusBar() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏
    }

}
